<?php
include 'serverInfo.php';
	
// Connect to MySQL database
mysql_connect(ServerInfo::HOST.':'.ServerInfo::PORT,ServerInfo::USERNAME,ServerInfo::PASSWORD);

$page = 1; 
// The current page
//$sortname = ''; 
// Sort column
//$sortorder = ''; 
// Sort order
$qtype = ''; 
// Search column
$query = ''; 
// Search string
// Get posted data
if (isset($_POST['page'])) 
{        
    $page = mysql_real_escape_string($_POST['page']);
}
//if (isset($_POST['sortname'])) 
//{        
//    $sortname = mysql_real_escape_string($_POST['sortname']);
//}
//if (isset($_POST['sortorder'])) 
//{        
//    $sortorder = mysql_real_escape_string($_POST['sortorder']);
//}
if (isset($_POST['qtype'])) 
{        
    $qtype = mysql_real_escape_string($_POST['qtype']);
}
if (isset($_POST['query'])) 
{        
    $query = mysql_real_escape_string($_POST['query']);    
}
if (isset($_POST['rp'])) 
{        
    $rp = mysql_real_escape_string($_POST['rp']);
}
// Setup sort and search SQL using posted data
//$sortSql = "order by $sortname $sortorder";
//$searchSql = ($qtype != '' && $query != '') ? "where $qtype = '$query'" : '';
// Get total count of records
//$sql = "DESC `".$_GET['schema']."`.`".$_GET['table']."`";
//$result = mysql_query($sql);
//$row = mysql_fetch_array($result);
//$total = $row[0];
//// Setup paging SQL
//$pageStart = ($page-1)*$rp;
//$limitSql = "limit $pageStart, $rp";

$sql = "DESC `".$_GET['schema']."`.`".$_GET['table']."`";

$results = mysql_query($sql);
//// Return JSON data
$data = array();
$data['page'] = 1;//$page;
$data['total'] = mysql_affected_rows();//$total;
$data['rows'] = array();
$extData = getExtendedData($_GET['schema'], $_GET['table'],$results);
mysql_data_seek($results, 0);
$idx=0;
while ($row = mysql_fetch_assoc($results)) 
{
    $key = $row['Field'];
    $row = array('id' => strval($idx++),'cell' => array($key,$extData[$key]['Alias'],$extData[$key]['Description'],$extData[$key]['Dictionary'], $row['Type'],$row['Null'],$row['Key'],$row['Default'],$row['Extra']));
    $data['rows'][] = $row;
}
echo json_encode($data);

function getExtendedData($schema,$table,$results)
{
    $sepChar = DIRECTORY_SEPARATOR;
    $filename = str_replace('/',DIRECTORY_SEPARATOR,$_SERVER['DOCUMENT_ROOT']).$sepChar."data".$sepChar.$schema."_".$table.".ext";
    // 如果扩展信息文件不存在，则创建一个空数据的文件
    if(!file_exists($filename))
    {
        $extData = array();
        while ($row = mysql_fetch_assoc($results))
        {
            $extRow = array();
            $extRow['Alias']='';
            $extRow['Description']='';
            $extRow['Dictionary']='';
            $extData[$row['Field']]=$extRow;
        }
        
        file_put_contents($filename,serialize($extData));
    }
    
    // 读取文件，反序列化后返回
    return unserialize(file_get_contents($filename));
}
?>
